import { useState, useRef, useEffect, forwardRef, useImperativeHandle } from "react";

export const HtmlAudio = forwardRef<{ destroy: () => void }, { onDestroy?: () => void }>(({ onDestroy }, ref) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [volume, setVolume] = useState(0.5);
  const [isLoop, setIsLoop] = useState(true);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  useImperativeHandle(ref, () => ({
    destroy: () => {
      if (audioRef.current) {
        console.log('🧹 手动销毁HTML5 Audio实例');
        audioRef.current.pause();
        audioRef.current.currentTime = 0;
        onDestroy?.();
      }
    }
  }));

  useEffect(() => {
    console.log('🔧 初始化HTML5 Audio实例, loop:', isLoop);
    
    // 检测iOS设备
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
    const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
    const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
    console.log('📱 设备检测 - iOS:', isIOS);
    console.log('📱 iOS版本:', iosVersion || '未知');
    console.log('📱 User Agent:', navigator.userAgent);
    console.log('📱 HTML5 Audio支持:', typeof Audio !== 'undefined');

    return () => {
      if (audioRef.current) {
        console.log('🧹 清理HTML5 Audio实例');
        audioRef.current.pause();
        audioRef.current.currentTime = 0;
        onDestroy?.();
      }
    };
  }, []);

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume;
    }
  }, [volume]);

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.loop = isLoop;
    }
  }, [isLoop]);

  const togglePlay = () => {
    if (!audioRef.current) {
      console.log('❌ Audio元素不存在');
      return;
    }

    if (isPlaying) {
      console.log('⏸️ 执行暂停操作');
      audioRef.current.pause();
    } else {
      console.log('▶️ 执行播放操作');
      audioRef.current.play().catch((error) => {
        console.error('❌ 播放失败:', error);
      });
    }
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newVolume = parseFloat(e.target.value);
    setVolume(newVolume);
  };

  const handleLoopToggle = () => {
    setIsLoop(!isLoop);
  };

  const handleTimeUpdate = () => {
    if (audioRef.current) {
      setCurrentTime(audioRef.current.currentTime);
    }
  };

  const handleLoadedMetadata = () => {
    if (audioRef.current) {
      setDuration(audioRef.current.duration);
      console.log('📥 音频元数据加载完成');
      console.log('🔍 音频时长:', audioRef.current.duration);
    }
  };

  const handlePlay = () => {
    console.log('▶️ onplay 触发');
    console.log('🔍 当前loop状态:', audioRef.current?.loop);
    console.log('🔍 当前音量:', audioRef.current?.volume);
    console.log('🔍 当前时间:', audioRef.current?.currentTime);
    console.log('🔍 音频时长:', audioRef.current?.duration);
    setIsPlaying(true);
  };

  const handlePause = () => {
    console.log('⏸️ onpause 触发');
    setIsPlaying(false);
  };

  const handleEnded = () => {
    console.log('🏁 onended 触发');
    console.log('🔍 当前loop状态:', audioRef.current?.loop);
    console.log('🔍 当前时间:', audioRef.current?.currentTime);
    console.log('🔍 音频时长:', audioRef.current?.duration);
    setIsPlaying(false);
  };

  const handleError = (e: React.SyntheticEvent<HTMLAudioElement, Event>) => {
    console.error('❌ 音频加载失败:', e);
    alert('音频文件加载失败，请检查网络连接');
  };

  const handleDebugInfo = () => {
    if (audioRef.current) {
      const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
      const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
      console.log('🔍 手动检查音频状态:');
      console.log('  - 播放状态:', !audioRef.current.paused);
      console.log('  - 循环状态:', audioRef.current.loop);
      console.log('  - 音频状态:', audioRef.current.readyState);
      console.log('  - iOS版本:', iosVersion || '未知');
      console.log('  - User Agent:', navigator.userAgent);
      console.log('  - 音频元素:', audioRef.current);
      console.log('  - 节点循环:', audioRef.current.loop);
      console.log('  - 节点结束:', audioRef.current.ended);
      console.log('  - 当前时间:', audioRef.current.currentTime);
      console.log('  - 音频时长:', audioRef.current.duration);
      console.log('  - 播放速率:', audioRef.current.playbackRate);
      console.log('  - 节点音量:', audioRef.current.volume);
      console.log('  - 节点静音:', audioRef.current.muted);
      console.log('  - 网络状态:', audioRef.current.networkState);
      console.log('  - 就绪状态:', audioRef.current.readyState);
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '400px', margin: '0 auto' }}>
      <h2>HTML5 Audio播放器</h2>
      
      {/* 隐藏的audio元素 */}
      <audio
        ref={audioRef}
        src="https://creation.codemao.cn/884/l31cw9bi.mpeg"
        loop={isLoop}
        onPlay={handlePlay}
        onPause={handlePause}
        onEnded={handleEnded}
        onTimeUpdate={handleTimeUpdate}
        onLoadedMetadata={handleLoadedMetadata}
        onError={handleError}
        preload="metadata"
      />
      
      {/* 播放控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <button
          onClick={togglePlay}
          style={{
            padding: '10px 20px',
            fontSize: '16px',
            backgroundColor: isPlaying ? '#ff4444' : '#4CAF50',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
            marginRight: '10px'
          }}
        >
          {isPlaying ? '停止' : '播放'}
        </button>
        <button
          onClick={handleDebugInfo}
          style={{
            padding: '10px 20px',
            fontSize: '14px',
            backgroundColor: '#2196F3',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer'
          }}
        >
          调试信息
        </button>
      </div>

      {/* 音量控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'block', marginBottom: '10px' }}>
          音量: {Math.round(volume * 100)}%
        </label>
        <input
          type="range"
          min="0"
          max="1"
          step="0.1"
          value={volume}
          onChange={handleVolumeChange}
          style={{ width: '100%' }}
        />
      </div>

      {/* 循环播放控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <input
            type="checkbox"
            checked={isLoop}
            onChange={handleLoopToggle}
            style={{ transform: 'scale(1.2)' }}
          />
          <span>循环播放</span>
        </label>
      </div>

      {/* 进度条 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'block', marginBottom: '10px' }}>
          进度: {currentTime.toFixed(2)}s / {duration.toFixed(2)}s
        </label>
        <input
          type="range"
          min="0"
          max={duration || 0}
          step="0.1"
          value={currentTime}
          onChange={(e) => {
            if (audioRef.current) {
              audioRef.current.currentTime = parseFloat(e.target.value);
            }
          }}
          style={{ width: '100%' }}
        />
      </div>

      {/* 状态显示区域 */}
      <div style={{ fontSize: '14px', color: '#666', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '5px' }}>
        <p>状态: {isPlaying ? '播放中' : '已停止'}</p>
        <p>音量: {Math.round(volume * 100)}%</p>
        <p>循环播放: {isLoop ? '开启' : '关闭'}</p>
        <p>设备: {(() => {
          const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
          if (isIOS) {
            const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
            const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
            return `iOS ${iosVersion || '未知版本'}`;
          }
          return '非iOS';
        })()}</p>
        {audioRef.current && (
          <>
            <p>音频状态: {audioRef.current.readyState}</p>
            <p>实际循环状态: {audioRef.current.loop ? '开启' : '关闭'}</p>
            <p>HTML5 Audio: 是</p>
            <p>音频时长: {duration ? duration.toFixed(2) + 's' : '未知'}</p>
            <p>当前时间: {currentTime.toFixed(2)}s</p>
            <p>播放速率: {audioRef.current.playbackRate}</p>
            <p>节点音量: {audioRef.current.volume}</p>
            <p>节点静音: {audioRef.current.muted ? '是' : '否'}</p>
            <p>网络状态: {audioRef.current.networkState}</p>
            <p>就绪状态: {audioRef.current.readyState}</p>
          </>
        )}
      </div>
    </div>
  );
});
